package main

import (
	"github.com/go-martini/martini"
	"github.com/martini-contrib/render"
	// "github.com/russross/blackfriday"

	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"regexp"
	"strings"
	"time"
)

// 利用 blackfriday 格式化markdown
func readMd(r render.Render, params martini.Params, req *http.Request) {

	var fname string
	var haveFile bool = false

	if len(params["fname"]) > 0 {

		if ExistMd(params["fname"]) {
			fname = params["fname"]
			haveFile = true
		}

		if !haveFile && ExistMd(params["fname"]+".md") {
			fname = params["fname"] + ".md"
			haveFile = true
		}

		if !haveFile && ExistMd(params["fname"]+"/index.md") {
			r.Redirect("/" + params["fname"] + "/index.md")
		}
	}

	log.Println("filename: ", fname)
	if !haveFile {
		r.Error(404)
	} else {
		fname = conf.MdPath + fname
		b, _ := ioutil.ReadFile(fname)
		// re := blackfriday.HtmlRenderer(1, "title", "")
		// md := blackfriday.Markdown(b, re, blackfriday.EXTENSION_TABLES+blackfriday.EXTENSION_FENCED_CODE)
		// md := blackfriday.MarkdownCommon(b)

		var title = regexp.MustCompile(`title\:\ (.*)`).FindSubmatch(b)
		var tags = regexp.MustCompile(`tags\:\ (.*)`).FindSubmatch(b)
		var dateTime = regexp.MustCompile(`date\:\ (.*)`).FindSubmatch(b)
		var updateTime = regexp.MustCompile(`update\:\ (.*)`).FindSubmatch(b)

		var Title, Tags, DateTime, UpdateTime string

		if len(title) < 2 {
			title = regexp.MustCompile(`#\ (.*)`).FindSubmatch(b)
		}

		if len(title) < 2 {
			Title = "Unkown"
		} else {
			Title = string(title[1])
		}

		if len(Tags) < 2 {
			Tags = "unkown"
		} else {
			Tags = string(tags[1])
		}

		if len(dateTime) < 2 {
			DateTime = time.Now().String()
		} else {
			DateTime = string(dateTime[1])
		}

		if len(updateTime) < 2 {
			UpdateTime = time.Now().String()
		} else {
			UpdateTime = string(updateTime[1])
		}

		Vdata := map[string]interface{}{
			"title":     Title,
			"tags":      Tags,
			"date":      DateTime,
			"update":    UpdateTime,
			"mdContent": string(b),
		}

		// jquery have the header X-Requested-With
		// log.Println(req.Header.Get("X-Requested-With"))

		if isAjax, _ := regexp.MatchString(`^application[//]json`, req.Header.Get("Accept")); isAjax {
			// if len(req.Header.Get("X-Requested-With")) > 0 {
			r.Header().Set("Access-Control-Allow-Origin", "*")
			r.JSON(200, Vdata)
		} else {
			r.HTML(200, "md", Vdata)
		}
	}
}

// 读取图片
func readImg(r render.Render, res http.ResponseWriter, params martini.Params) {
	fname := conf.MdPath + params["fname"] + "." + params["fimg"]
	if ExistFile(fname) {
		b, _ := ioutil.ReadFile(fname)
		res.Header().Set("ContentType", "image/"+params["fimg"])
		res.Write(b)
	} else {
		r.Error(404)
	}
}

// 获取目录
func readMenus(r render.Render, params martini.Params, req *http.Request) {
	bpath := conf.MdPath
	Bpath := "/"
	if len(params["fdir"]) > 0 {
		bpath = conf.MdPath + params["fdir"]
		Bpath = "/" + params["fdir"] + "/"
	}

	// if isdir, err := os.Stat(bpath); err != nil && isdir.IsDir() {
	Vdata, _ := doHashWalk(bpath)

	if isAjax, _ := regexp.MatchString(`^application/json`, req.Header.Get("Accept")); isAjax {
		// if len(req.Header.Get("X-Requested-With")) > 0 {
		r.Header().Set("Access-Control-Allow-Origin", "*")
		r.JSON(200, Vdata)
	} else {
		log.Println(Bpath)
		r.HTML(200, "menus", map[string]interface{}{"title": Bpath, "bpath": Bpath, "menus": Vdata})
	}
}

type mdFile struct {
	MdPath string
	Mdc    string
}

func UpdateMd(r render.Render, params martini.Params, req *http.Request) {

	var md mdFile
	Status := 1
	Msg := "ok! you have created one file!"

	// 对an
	postValue, err := ioutil.ReadAll(req.Body)
	defer req.Body.Close()
	if err != nil {
		log.Println(err.Error())
		Status = 0
	}
	json.Unmarshal(postValue, &md)

	if len(params["fname"]) > 3 {
		md.MdPath = params["fname"] + ".md"
	}

	if ExistMd(md.MdPath) {
		Msg = "ok! you have update one file!"
	} else {
		mkDirs(md.MdPath)
	}

	mdf, err := os.OpenFile(conf.MdPath+md.MdPath, os.O_RDWR|os.O_CREATE, 0644)
	defer mdf.Close()
	if err != nil {
		log.Println(err.Error())
	}

	ret, err := mdf.WriteString(md.Mdc)

	if err != nil {
		log.Println(err.Error())
		Status = 0
	}

	if Status == 0 {
		Msg = "sorry , I have a bug or you have a error!"
	}

	log.Println("wirte file : ", ret)

	Vdata := map[string]interface{}{
		"path":   strings.Replace(md.MdPath, "\\", "/", -1),
		"status": Status,
		"msg":    Msg,
	}

	r.JSON(200, Vdata)

}
